package concurrents.pool;

import java.util.List;
import java.util.Vector;

/**
 * 简单线程池的实现
 * 不依赖JDK提供的框架
 *
 * @author glogo
 *
 */
public class MyThreadPoolDemo2 {

	private static MyThreadPoolDemo2 instance = null;
	
	private List<PThread> idleThreads;	//空闲队列
	
	private int threadCounter;		//已有线程总数
	private boolean isShutDown = false;
	
	private MyThreadPoolDemo2(){
		this.idleThreads = new Vector<>(5);
		threadCounter = 0;
	}
	
	public synchronized static MyThreadPoolDemo2 getInstance(){
		if(instance == null)
			instance = new MyThreadPoolDemo2();
		return instance;
	}
	
	//将线程放入池中
	protected synchronized void repool(PThread repoolingThread){
		if(!isShutDown){
			idleThreads.add(repoolingThread);
		}else{
			repoolingThread.shutDown();
		}
	}
	
	//停止池中所有线程
	public synchronized void shutdown(){
		isShutDown = true;
		for(int threadIndex = 0; threadIndex < idleThreads.size(); threadIndex++){
			PThread idleThread = idleThreads.get(threadIndex);
			idleThread.shutDown();
		}
	}
	
	public synchronized void start(Runnable target){
		PThread thread = null;
		if(idleThreads.size() > 0){
			int lastIndex = idleThreads.size() - 1;
			thread = idleThreads.get(lastIndex);
			idleThreads.remove(lastIndex);
			thread.setTarget(thread);
		}else{
			threadCounter++;
			thread = new PThread(target, "PThread # " + threadCounter, this);
			thread.start();
		}
	}
	
}
